package com.sgcc.pda.hzaidl.impl;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.RemoteException;
import android.text.TextUtils;
import android.widget.CheckBox;


import com.sgcc.pda.data.dao.SharepreferenceUtil;
import com.sgcc.pda.hw.IScannerReceiveDataCallback;
import com.sgcc.pda.hw.ReturnResult;
import com.sgcc.pda.hzaidl.entity.HardWareCallback;


import com.sgcc.pda.ui.ZBarActivity;
import com.sgcc.platforminterface.PlatfInterfManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import cn.bingoogolapple.qrcode.core.CameraPreview;
import cn.bingoogolapple.qrcode.core.ScanBoxView;


/**
 * @创建者：suven on 2019/12/17 21:48
 * @描述：
 * @版本：1.0
 * @修改人：
 * @修改时间：
 * @修改说明：
 * @修改版本：
 */
public class ScannerManager {
    private static ScannerManager mInstance;
    /**
     * 平台是否支持相机扫码，默认不支持。
     */
    private boolean isPlatformSupportCameraScan = false;

    /**
     * 单例
     *
     * @return
     */
    public static synchronized ScannerManager getInstance() {
        if (mInstance == null) {
            mInstance = new ScannerManager();
        }
        return mInstance;
    }

    public static final String BROADCAST_PERMISSION_ZXING = "com.sgcc.pda.hw.ui.activity.ZxingActivity";
    public static final String EXTRA_DATA = "data";
    private HardWareCallback callBack;


    /**
     * 接收zxing状态广播
     */
    private final BroadcastReceiver zXingReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 发现设备
            if (BROADCAST_PERMISSION_ZXING.equals(action)) {
                String data = intent.getStringExtra(EXTRA_DATA);
                final List<String> datas = new ArrayList<>();
                datas.add(data);
                if (callBack != null) {
                    ReturnResult returnResult = new ReturnResult();
                    returnResult.setCode(TextUtils.isEmpty(data) ? -1 : 0);
                    returnResult.setDatas(datas);
                    callBack.onReceiverData(returnResult);
                }
                unregisterReceiver(context);
            }
        }
    };


    /**
     * 注册广播
     */

    //注册广播
    public final void registerReceiver(Context context) {
        LocalBroadcastManager.getInstance(context).unregisterReceiver(zXingReceiver);
        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_PERMISSION_ZXING);
        LocalBroadcastManager.getInstance(context).registerReceiver(zXingReceiver, filter);
    }

    //反注册广播
    public final void unregisterReceiver(Context context) {
        try {
            LocalBroadcastManager.getInstance(context).unregisterReceiver(zXingReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 扫描条形码二维码
     *
     * @param hardWareCallback 返回结果回调
     *                         ReturnResult  :int code  0 成功  其他失败
     *                         :List<String> datas（code==0）:
     *                         0:data      返回扫描到的结果
     *                         :List<String> datas(code==其他): size==0
     */
    public void decodeScan(final HardWareCallback hardWareCallback) throws RemoteException {
        if (PlatfInterfManager.getInstance().isSpeed()) {
            // 手机模式、背夹模式，且平台不支持相机扫码。使用本地实现的相机扫码
            if ((isPhoneMode() || isBluetoothMode()) && !isPlatformSupportCameraScan()) {
                scanCamera(hardWareCallback);
            } else {
                postDecode(hardWareCallback);
            }
        } else
            com.sgcc.pda.hw.impl.ScannerManager.getInstance().getScannerManager().
                    decodeScan(new IScannerReceiveDataCallback.Stub() {
                        @Override
                        public void onScannerReceiverData(ReturnResult returnResult) throws RemoteException {
                            if (hardWareCallback != null)
                                hardWareCallback.onReceiverData(returnResult);
                        }
                    });
    }

    /**
     * 设置平台是否支持相机扫码    true为支持，false 为不支持
     * 中台融e通在 versionCode124之后版本，背夹模式下可以直接postDecode 调用相机扫码
     * 平台极速版 应该还不支持
     * 2020.7.31
     *
     * @return
     */
    public void setPlatformSupportCameraScan(boolean isPlatformSupportCameraScan) {
        this.isPlatformSupportCameraScan = isPlatformSupportCameraScan;
    }

    /**
     * 极速版版本。平台是否支持相机扫码  ，若是支持，则背夹模式下 直接使用平台提供的，
     * 不再调用scanCamera，直接postDecode
     *
     * @return
     */
    private boolean isPlatformSupportCameraScan() {
        return isPlatformSupportCameraScan;
    }

    private void scanCamera(HardWareCallback hardWareCallback) {
        callBack = hardWareCallback;
        Context context = PlatfInterfManager.getInstance().getContext();
        registerReceiver(context);
        //扫描
        Intent intent = new Intent(context, ZBarActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private void postDecode(HardWareCallback hardWareCallback) {
        try {
            JSONObject jb = new JSONObject();
            jb.put("timeout", 10000);
            HardWareUtil.requestHardwareData("scanner_decodeScan", jb.toString(), hardWareCallback);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 扫描头通讯关闭和电源关闭
     *
     * @return 0：成功 其它：错误号
     */
    public ReturnResult Scanner_deInit() throws RemoteException {
        if (PlatfInterfManager.getInstance().isSpeed()) {
            if (isBluetoothMode()) {
                ReturnResult returnResult = new ReturnResult();
                returnResult.setCode(0);
                ArrayList datas = new ArrayList<String>();
                datas.add("背夹模式无需关闭");
                returnResult.setDatas(datas);
                return returnResult;
            } else {
                return HardWareUtil.requestHardwareData("scanner_ScannerDeInit");
            }
        } else
            return com.sgcc.pda.hw.impl.ScannerManager.getInstance().getScannerManager().Scanner_deInit();
    }

    /**
     * 是不是背夹模式
     *
     * @return
     */
    public static boolean isBluetoothMode() {
        return SharepreferenceUtil.isBluetoothMode(PlatfInterfManager.getInstance().getContext());
    }

    /**
     * 是不是手机模式
     *
     * @return
     */
    public static boolean isPhoneMode() {
        return SharepreferenceUtil.isPhoneMode(PlatfInterfManager.getInstance().getContext());
    }

    public void setConfig(CameraConfig config) {
        this.config = config;
    }

    public CameraConfig getConfig() {
        return config;
    }

    private CameraConfig config;

    public interface CameraConfig {
        void onCreate(ScanBoxView scanBoxView, CameraPreview cameraPreview, CheckBox cbFlashLamp);

        String provideOnCameraAmbientBrightnessChangedTips();
    }
}
